/**
 * @author Paulo Faria Reis
 * @created 22 Mar 2012
 *
 */
package networkoperations;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.MulticastSocket;
import java.util.Random;

import controller.DataStore;

/**
 * @author Paulo Faria Reis
 * Receives a string with the text to find, multicast channel address and port.
 */
public class Searcher {
	DataStore dataStorage;
	
	// Inner class to store the result of a single file search.
	public class Match {
		long size;
		String hash;
		String filename;

		public Match(String hash, long size, String filename) {
			this.hash = hash;
			this.size = size;
			this.filename = filename;
		}

		long getSize() {
			return size;
		}

		String getHash() {
			return hash;
		}

		String getFilename() {
			return filename;
		}		
	}

	MulticastSocket controlSocket;
	String searchString;
	String fileHash;
	Match[] matchesFound; 
	/**
	 * @author Paulo Faria Reis
	 * @throws IOException 
	 */
	public Searcher(String whatToFind, DataStore dataStor) throws IOException{
		// create a random int for id
		Random randomChunk = new Random();
		int randomInt = randomChunk.nextInt(899999999);
		randomInt += 100000000;	// randomInt will be between 100000000 and 999999999, that is 9 digits wide.
		// Message of packet for the search.
		byte[] msgOut = ("SEARCH id" + randomInt + " " + whatToFind).getBytes();
		
		// Send multicast packet to control channel to search for files.
		DatagramPacket announcer = new DatagramPacket(msgOut, msgOut.length, dataStorage.getMcAddress(), dataStorage.getControlPort());
		controlSocket = new MulticastSocket(dataStorage.getControlPort());
		controlSocket.joinGroup(dataStorage.getMcAddress());
		controlSocket.setTimeToLive(1);
		controlSocket.send(announcer);
		
		// TODO cicle time controled to received multicast 


		// Present search result and let user select.
		
		// place data on desiredFiles to know what files are to be received.
		
		controlSocket.leaveGroup(dataStorage.getMcAddress());
		controlSocket.close();
	}


	public String fileHashSelected() {
		return "a";
	}


}
